<template>
  <div class="login-container">
    <el-card class="login-card" header="用户登录">
      <el-form :model="form" :rules="rules" ref="formRef" @submit.prevent="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading" style="width: 100%;">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        <router-link to="/register">还没有账户？去注册</router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useAuth } from '@/composables/useAuth'
import { ElMessage } from 'element-plus'

const formRef = ref(null)
const loading = ref(false)
const form = ref({
  username: '',
  password: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const { login } = useAuth()

const handleLogin = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await login(form.value);
        ElMessage.success('登录成功！');
        // 登录成功后，useAuth 会自动跳转，这里不需要额外操作
      } catch (error) {
        const message = error.response?.data?.error || '登录失败，请检查您的凭据';
        ElMessage.error(message);
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw; /* Use vw for full viewport width */
  background: linear-gradient(to right, #6a11cb, #2575fc);
}
.login-card {
  width: 400px;
}
.card-header {
  text-align: center;
  font-size: 20px;
}
.register-link {
  text-align: center;
  margin-top: 10px;
}
</style>